/**
 * Created by GJS on 2020/2/14.
 */

import { DeviceEventEmitter, NativeEventEmitter, NativeModules, Platform } from 'react-native';
import { EventEmitter } from 'events';
import { Actions } from 'react-native-router-flux';

// const { RCTVoiceAssistant } = NativeModules;
const RCTVoiceAssistant = NativeModules.RCTVoiceAssistant || NativeModules.VoiceAssistant;

// Event emitter to dispatch request and response from VoiceAssistant.
// const emitter = new EventEmitter();
let emitter = Platform.OS == 'ios' ? new NativeEventEmitter(RCTVoiceAssistant) : DeviceEventEmitter;
if (!emitter) {
  emitter = NativeAppEventEmitter;
}

emitter.addListener('VoiceAssistant_Resp', resp => {
  /*
  // resp 完全由AIUI技能工作室后台配置返回->内容（信源）(指真正对用户有用的内容)
  // 原生会封装成一个对象，至少包含 name，而 param 可选
  let name = resp.name;
  let param = resp.param;
  if (Actions && Actions[name]) { // 默认路由跳转
    (Actions[name])({assistantParam: param});
  } else { // 否则广播出去
    emitter.emit(VoiceAssistant.ConstantEmitResult, resp);
  }
  */

  console.log("resp:" + JSON.stringify(resp));
  if ((typeof resp) === 'string') {
    resp = JSON.parse(resp);
  }
  if (resp.intent.semantic === undefined || resp.intent.semantic.length === 0) {
    return;
  }

  const semantic = resp.intent.semantic[0];
  let result = VoiceAssistant.handleSemantic('function', semantic);
  // 广播筛选后的结果 result 和 原数据 resp
  emitter.emit(VoiceAssistant.ConstantEmitResult, result, resp);

});

export default class VoiceAssistant {
  static get ConstantEmitResult() {return 'VoiceAssistant_EmitResult'}
  static openVoiceAssistant(options) {
    console.log('RCTVoiceAssistant:' + NativeModules.RCTVoiceAssistant);
    console.log('NativeModules.VoiceAssistant:' + NativeModules.VoiceAssistant);
    return RCTVoiceAssistant.openVoiceAssistant(options);
  }
  static closeVoiceAssistant() {
    return RCTVoiceAssistant.closeVoiceAssistant();
  }

  // 处理数据
  static handleSemantic(key, semantic) {
    let result = semantic;
    if (typeof key === 'string' && semantic) {
      const slots = semantic.slots;
      let scene_key = undefined;
      let index = -1;
      // 是否有配置名为 key 的槽：
      for(let i=0; i<slots.length; i++) {
        const slot = slots[i];
        if (slot.name.startsWith(key)) {
          index = i;
          scene_key = slot.normValue;
          break;
        }
      }
      // 如果有，取路由名 scene_key，否则原样返回 semantic 数组
      if (index !== -1) {
        slots.splice(index, 1);
        result = {
          intent: semantic.intent,
          scene_key: scene_key,
          slots: slots,
        };
      }
    }
    return result;
  }
}
